import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import {UserService} from '../services/user.service';
import {User} from '../models/user';
import {Observable} from 'rxjs';
import {LoginService} from './login.service';

@Component({
  selector: 'app-login',
  styles: ['login.css'],
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit, OnDestroy {
  public password: string;
  public email: string;

  constructor(
    private userServ: UserService,
    private loginService: LoginService,
    private router: Router
  ) {
  }

  public ngOnInit() {
    window.dispatchEvent( new Event( 'resize' ) );
    document.body.className = 'hold-transition login-page';
  }

  public login() {
    // test
    // if ( 1 === 1 ) {
    //   const user1 = new User( {
    //       avatarUrl: 'assets/img/user2-160x160.jpg',
    //       email: 'weber.antoine@outlook.com',
    //       username: 'WEBER'
    //   } );
    //   user1.connected = true;
    //   this.userServ.setCurrent(user1);
    //   this.router.navigate( ['home'] );
    // } else {
    //   // je recupere l'erreur du php
    //   // et on le place dans un label, ou un toaster
    // }

    const user = new User( {
      username: this.email,
      password: this.password
    } );
    this.loginService.login(user).subscribe(resp => {
      if (resp === '-1') {
        alert('用户不存在');
      } else if (resp === '-2') {
        alert('密码错误');
      } else {
        localStorage.setItem('token', resp);
        user.avatarUrl = 'assets/img/user2-160x160.jpg';
        user.connected = true;
        this.userServ.setCurrent(user);
        this.router.navigate( ['home'] );
        // this.router.navigateByUrl('home');
      }
    });
  }
  public ngOnDestroy() {
    document.body.className = '';
  }
}
